package study.zookeeper.controller.curator;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
public class _3DistributedController {

    private String path = "/super";

    @Autowired
    private CuratorFramework client;

    @RequestMapping("/increment")
    public Map<String, Object> increment() throws Exception {
        //
        RetryNTimes retry = new RetryNTimes(3, 1000);
        DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, path, retry);
        //
        AtomicValue<Integer> value = atomicInteger.increment();

        Map<String, Object> data = Maps.newHashMap();
        data.put("succeeded", value.succeeded());
        data.put("preValue", value.preValue());
        data.put("postValue", value.postValue());
        return data;
    }
}
